﻿using mozhi.smarterp.BasicData.TaxRates;
using mozhi.smarterp.BasicData.Warehouses.Repositories;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Services;
using Volo.Abp.Guids;

namespace mozhi.smarterp.BasicData.Warehouses.Services
{
    public class WarehouseManager : DomainService
    {
        private IWarehouseRepository _repository;
        private IGuidGenerator _guidGenerator;

        public WarehouseManager(IWarehouseRepository repository , IGuidGenerator guidGenerator)
        {
            _repository = repository;
            _guidGenerator = guidGenerator;
        }

        public async Task<Warehouse> GetAsync(Guid? id, string code, string name,string address , bool activateLocation,  bool activated)
        {
            var matchCount = await _repository.GetCountAsync(code, null, id) + await _repository.GetCountAsync(null, name, id);

            if (matchCount > 0)
                throw new UserFriendlyException("编码或者名称已经存在", "100000");

            Warehouse warehouse;

            if (id.HasValue)
            {
                warehouse = await _repository.GetAsync(id.Value);

                if (warehouse == null)
                    throw new UserFriendlyException($"仓库：{id}不存在", "100000");

                warehouse.Change(code , name , address , activateLocation , activated);
            }
            else
                warehouse = new Warehouse(_guidGenerator.Create(), code, name, address, activateLocation, activated);

            return warehouse;
        }
    }
}
